package cn.edu.neusoft.demo.hospital2.Dao;

import cn.edu.neusoft.demo.hospital2.pojo.Department;
import cn.edu.neusoft.demo.hospital2.pojo.Room;
import cn.edu.neusoft.demo.hospital2.pojo.SpecialClinic;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface DepartmentDao extends BaseMapper<Department> {

    List<Department> selectAll();
    Department selectById(int departmentId);
    int updateById(Department department);
    int insert(Department department);
    int deleteById(int departmentId);

    // 查询子科室列表
    @Select("SELECT * FROM department WHERE parent_id = #{parentId} ORDER BY department_id ASC")
    List<Department> selectChildrenByParentId(@Param("parentId") Integer parentId);

    // 查询科室树
    @Select("SELECT * FROM department WHERE level = 1")
    List<Department> selectTopLevelDepartments();

    // 查询科室关联的诊室
    @Select("SELECT * FROM room WHERE depart_id1 = #{deptId} OR depart_id2 = #{deptId}")
    List<Room> selectRoomsByDepartmentId(@Param("deptId") Integer deptId);

    // 查询科室关联的特色门诊
    @Select("SELECT * FROM clinic WHERE department_id = #{deptId}")
    List<SpecialClinic> selectClinicsByDepartmentId(@Param("deptId") Integer deptId);

    // 根据ID查询科室
    @Select("SELECT * FROM department WHERE department_id = #{id}")
    Department selectDepartmentById(@Param("id") Integer id);

    // 更新科室
    @Update("UPDATE department SET department_name = #{departmentName}, level = #{level}, " +
            "parent_id = #{parentId} WHERE department_id = #{departmentId}")
    int updateDepartment(Department department);

    // 删除科室
    @Delete("DELETE FROM department WHERE department_id = #{id}")
    int deleteDepartmentById(@Param("id") Integer id);

    // 查询根部门
    @Select("SELECT * FROM department WHERE parent_id = 0 OR parent_id IS NULL")
    @Results({
            @Result(property = "departmentId", column = "department_id"),
            @Result(property = "children", column = "department_id",
                    many = @Many(select = "findChildrenByParentId"))
    })
    List<Department> findRootDepartments();

    @Select("SELECT * FROM department WHERE parent_id = #{parentId}")
    List<Department> findChildrenByParentId(@Param("parentId") int parentId);
}
